package com.tansun.easycare.rule.sysparam.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.tansun.easycare.rule.common.JsonMessage;
import com.tansun.easycare.rule.common.ResMessage;
import com.tansun.easycare.rule.common.RuleBaseController;
import com.tansun.easycare.rule.common.model.ResponseVO;
import com.tansun.easycare.rule.datamodel.dao.RuleDatasetDao;
import com.tansun.easycare.rule.datamodel.entity.RuleDataparams;
import com.tansun.easycare.rule.datamodel.entity.RuleDataset;
import com.tansun.easycare.rule.datamodel.service.RuleDataparamsService;
import com.tansun.easycare.rule.exception.BizException;

@Controller
@RequestMapping(value = "/ruleProj/sysparam")
public class SysParamController extends RuleBaseController {

    @Autowired
    private RuleDataparamsService ruleDataparamsService;

    @Autowired
    private RuleDatasetDao ruleDatasetDao;

    @RequestMapping("list")
    public String index(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws Exception {
        RuleDataset dataInfo = new RuleDataset();
        dataInfo.setName("SYS_RULE");
        RuleDataset ruleDataset = null;
        List<RuleDataset> list = this.ruleDatasetDao.findList(dataInfo);
        if (list == null || list.size() == 0)
            throw new BizException("E-100001");
        if (list != null && list.size() > 0) {
            ruleDataset = list.get(0);
        }
        String datasetId = ruleDataset.getId();


        RuleDataparams ruleDataparams = new RuleDataparams();
        ruleDataparams.setProjectcode("SYS_RULE");

        ruleDataparams.setDatasetId(datasetId);
       
        ruleDataparams.getPage().setPageSize(10);
      
        List<RuleDataparams> plist = this.ruleDataparamsService.findList(ruleDataparams);
        PageInfo<RuleDataparams> page = new PageInfo<>(plist);

        map.put("dataset", ruleDataset);
        map.put("page", page);
        return "rule/sysparam/index";

    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public ResMessage saveOrUpdateParam(@RequestBody RuleDataparams ruleParam) {
        ResMessage res = new ResMessage();
        res.setCode("1");
        try {
            this.ruleDataparamsService.save(ruleParam);
        } catch (Exception e) {
            res.setCode("0");
        }
        return res;

    }

    @RequestMapping("getRuleDataParam")
    @ResponseBody
    public ResponseVO findDataparams(String id) {
        ResponseVO responseVO = new ResponseVO();
        responseVO.setStatus(200);
        if (StringUtils.isEmpty(id)) {
            responseVO.setData(new RuleDataparams());
            return responseVO;
        }
        RuleDataparams rDataparams = this.ruleDataparamsService.get(id);
        responseVO.setData(rDataparams);
        return responseVO;

    }

    @RequestMapping("copyParam")
    @ResponseBody
    public JsonMessage copyParam(String id) {
        JsonMessage resMessage = new JsonMessage();
        resMessage.setResult(true);

        RuleDataparams rDataparams = this.ruleDataparamsService.get(id);

        RuleDataparams copyParams = new RuleDataparams();
        try {
            BeanUtils.copyProperties(copyParams, rDataparams);
            copyParams.setId(null);
            copyParams.setChzn(rDataparams.getChzn() + "_copy");
            copyParams.setName(rDataparams.getName() + "_copy");
            this.ruleDataparamsService.save(copyParams);
        } catch (Exception e) {
            resMessage.setResult(false);
            resMessage.setMessage(e.getMessage());
        }
        return resMessage;

    }

    @RequestMapping("delect")
    @ResponseBody
    public String deleDataParam(@RequestParam("ids[]") String[] ids) {
        ResMessage msg = new ResMessage();
        msg.setCode("success");

        if (ids == null) {
            msg = new ResMessage("failure", "删除失败，参数有误");
            return JSONArray.toJSONString(msg);
        }
        boolean success;
        try {
            for (String id : ids) {
                this.ruleDataparamsService.deleteRuleDataparamsById(id);
            }
            success = true;
        } catch (Exception e) {
            logger.debug(ExceptionUtils.getStackTrace(e));

            msg = new ResMessage("failure", "删除失败，读写文件出错或者会话过期，尝试刷新");
            return JSONArray.toJSONString(msg);
        }
        if (!success) {
            msg = new ResMessage("failure", "删除失败，没有找到对应数据");
            return JSONArray.toJSONString(msg);
        }
        msg = new ResMessage("success", "删除成功");
        return JSONArray.toJSONString(msg);

    }

    @RequestMapping("nameUniqueCheck")
    @ResponseBody
    public ResMessage nameUniqueCheck(HttpServletRequest request, String datasetId, String key, String svalue, String paramId) {
        ResMessage res = new ResMessage();
        res.setCode("1");
        RuleDataparams ruleInfo = new RuleDataparams();
        ruleInfo.setDatasetId(datasetId);
        if ("name".equals(key)) {

            ruleInfo.setName(svalue);
        } else if ("chzn".equals(key)) {
            ruleInfo.setChzn(svalue);
        }
        List<RuleDataparams> list = this.ruleDataparamsService.findList(ruleInfo);
        if (list != null && list.size() > 0) {
            if (StringUtils.isEmpty(paramId) || !list.get(0).getId().equals(paramId)) {
                res.setCode("0");
                if ("name".equals(key)) {
                    res.setMsg("变量名称已经存在！");
                } else {
                    res.setMsg("变量中文名称已经存在！");
                }
            }
        }

        return res;
    }
}
